<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .box{
      width: 100px;
      height: 100px;
      background-color: red;
      position: absolute;
      left: 0;
      top: 0;
    }
  </style>
</head>
<body>
  <div class="box"></div>
  <script>
    // async&await
    // await 后面一定要跟一个promise对象
    function move(ele, attr, target){
      return new Promise((resolve, reject) => {
        let start = parseFloat(window.getComputedStyle(ele, null)[attr]);
        let dis = (target - start) / Math.abs(target - start);
        let speed = dis * 5;

        function fn(){
          let now = parseFloat(window.getComputedStyle(ele, null)[attr]);
          if(now == target){
            resolve('运动完成');
          } else {
            ele.style[attr] = now + speed + 'px';
            // 异步
            window.requestAnimationFrame(fn); // 性能更好
            // setTimeout(fn, 10);
          }
        }

        fn()
      })
    }

    let ele = document.querySelector('.box');

    async function asyncAwait(){
      try {
        let res = await move(ele, 'left', 200);
        console.log(res);
        await move(ele, 'top', 200);
        await move(ele, 'left', 0);
        await move(ele, 'top', 0);
      }catch(err){
        console.log(err);
      }
    }

    asyncAwait();
  </script>
</body>
</html>